<?php

namespace App\Http\Controllers\API\Pad;

use App\Http\Controllers\AppBaseController;
use App\Models\ParkInfo;
use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Passport\Passport;
use Laravel\Passport\Token;


class LoginAndLogoutController extends AppBaseController
{
    public function __construct()
    {
        $this->content = array();
        $this->clientId = config('custom.pad_client_id');
    }

    public function login(Request $request)
    {
        $this->validate($request, ['name' => 'required', 'password' => 'required']);

        $user = User::where('name', $request->get('name'))->first();
        if ($user && \Hash::check($request->get('password'), $user->password)) {
            if ($user->flag == 1) {
                return $this->sendError('账号已被冻结，请咨询管理员');
            }

            Passport::personalAccessClient($this->clientId);

            //生成token
            Token::where('user_id', $user->id)->where('client_id', $this->clientId)->delete();
            \Auth::setUser($user);

            //查询对应的车场和车道
            $parks = $this->getParkCodes($this->getUserParks());


            $parks = ParkInfo::whereIn('park_code', $parks)
                ->with(['parkChannels' => function ($query) {
                    return $query->where('type', 140);
                }])
                ->select(['parking_type', 'park_code', 'parking_type','parking_name','type_code'])
                ->get();

            //构建返回数据
            $pick_up_parks = $parks->where('type_code', 222);
            $storage_parks = $parks->where('type_code', 221);
            $data['pick_up_parks'] = $pick_up_parks ? $pick_up_parks->values()->toArray() : [];
            $data['storage_parks'] = $storage_parks ? $storage_parks->values()->toArray() : [];
            $data['token'] = 'Bearer ' . $user->createToken($user->name)->accessToken;


            return $this->sendResponse($data, '登录成功');
        }

        return $this->sendError('用户名或密码不正确');
    }

    /**
     * 删除token并注销
     *
     * @return mixed
     */
    public function logout()
    {
        $user = \Auth::user();

        Token::where('user_id', $user->id)->where('client_id', $this->clientId)->delete();

        return $this->sendResponse([], '退出成功');
    }
}
